<template>
  <div id="FileResource">
    <a-form layout="inline" style="margin-bottom: 8px">
      <a-form-item label="选择课程" class="searchItem">
        <a-select
          v-model="coursePlanId"
          placeholder="请输入"
          style="width: 200px"
        >
          <a-select-option
            v-for="item in courseList"
            :key="item.id"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="关键字" class="searchItem">
        <a-input v-model="keyword" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="getData"> 查询 </a-button>
      </a-form-item>
    </a-form>
    <div style="display: flex; justify-content: flex-end">
      <a-upload
        ref="uploadRef"
        class="upload"
        name="file"
        :data="getUploadParams"
        :before-upload="handleBeforeUpload"
        :multiple="true"
        :show-upload-list="false"
        action="/sys/resources"
      >
        <a-button type="primary" style="margin-left: 8px">导入</a-button>
      </a-upload>
    </div>
    <a-table
      :scroll="{ y: 450 }"
      :columns="columns"
      style="margin-top: 30px"
      :data-source="tableData"
      :pagination="tablePagination"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :rowKey="(record, index) => index"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button type="primary" @click="downLoad(record)">预览</a-button>
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="downLoad(record)"
          >下载</a-button
        >
        <a-button
          type="danger"
          style="margin-left: 10px"
          @click="deleteClick(record)"
          >删除</a-button
        >
      </template>
    </a-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      courseList: [], //课程下拉列表
      coursePlanId: null, //课程所选中的值
      keyword: null, //关键字
      selectedRowKeys: [],
      columns: [
        //主页table列的配置
        {
          title: "课程名称",
          dataIndex: "courseName",
          customRender: (text, record) => {
            return record.courseName ? record.courseName : "—";
          },
        },
        {
          title: "文件名称",
          dataIndex: "name",
          customRender: (text, record) => {
            return record.name ? record.name : "—";
          },
        },
        {
          title: "文件类型",
          dataIndex: "type",
          customRender: (text, record) => {
            return record.type ? record.type : "—";
          },
        },
        {
          title: "文件地址",
          dataIndex: "url",
          customRender: (text, record) => {
            return record.url ? record.url : "—";
          },
        },
        {
          title: "操作",
          width: 300,
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [
        //主页表格的数据
      ],
      tablePagination: {
        //主页表格的分页器
        total: 0,
        current: 1,
        size: "10",
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true, //是否可以改变 pageSize
      },
    };
  },
  created() {
    this.getData(); //获取列表数据
    this.getCourseList(); //获取课程列表的下拉
  },
  methods: {
    downLoad(row) {
      const token = localStorage.getItem("token");
      const url = `http://192.168.1.195:8011${row.url}?token=${token}`;
      window.open(url);
    },
    // downLoad(record) {
    //   const fileUrl = "http://192.168.1.165:8011"+record.url; // 文件路径
    //   const fileName = record.name || "downloaded-file"; // 自定义文件名
    //   const token = localStorage.getItem("token"); // 获取 token

    //   // 使用 axios 下载文件
    //   this.$axios
    //     .get(fileUrl, {
    //       headers: { Authorization: `Bearer ${token}` }, // 携带 Token
    //       responseType: "blob", // 处理为文件流
    //     })
    //     .then((response) => {
    //       const blob = new Blob([response.data]); // 创建 Blob 对象
    //       const link = document.createElement("a");
    //       link.href = window.URL.createObjectURL(blob); // 创建临时 URL
    //       link.download = fileName; // 设置文件名
    //       link.click(); // 触发下载
    //       window.URL.revokeObjectURL(link.href); // 释放 URL
    //     })
    //     .catch((error) => {
    //       console.error("文件下载失败", error);
    //       this.$message.error("文件下载失败，请稍后重试");
    //     });
    // },
    deleteClick(row) {
      //点击删除
      let params = {
        ids: row.id,
      };
      let that = this;
      this.$confirm({
        title: "确认删除?",
        content: "您确定要删除此项吗?",
        onOk() {
          that.$axios.delete("/sys/resources", { params }).then((res) => {
            that.$message.success("删除成功");
            that.getData();
          });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
    getUploadParams(file) {
      // 动态返回参数，根据文件的类型、大小等来决定要上传的参数
      return {
        name: file.name, //文件名
        desc: null, //文件描述
        type: file.type, // 文件类型
        coursePlanId: this.coursePlanId, //课程计划id
      };
    },
    handleBeforeUpload(file) {
      //文件上传的上传文件弹出框弹出之前的回调
      if (!this.coursePlanId) {
        this.$message.warning("请选择课程");
        return false; // 阻止文件上传
      } else {
        return true;
      }
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async getData() {
      let data = await this.$axios.get("/sys/resources/getExceptType", {
        //该接口是查询除了指定类型type的其他所有数据,这里是查除了model类型的所有数据
        params: {
          type: "model",
          // page: this.tablePagination.current,
          // limit: this.tablePagination.size,
          // courseName: this.coursePlanId, //课程名称
          // questionTopic: this.keyword, //关键字(也是题目内容)
        },
      });
      this.tableData = data.response;
      this.tablePagination.total = data.response.length;
    },

    async getCourseList() {
      //获取课程的下拉列表
      let data = await this.$axios.get("/sys/coursePlan/page");
      this.courseList = data.response;
    },
  },
};
</script>

<style lang="scss">
#FileResource {
  .upload {
    position: relative;
    .ant-upload-list {
      position: absolute;
      right: 0;
      .ant-upload-list-item {
        width: 200px;
      }
    }
  }
}
</style>